<template>
  <div class="app-container">
    <el-card style="margin: 15px; min-height: calc(100vh - 111px);">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="宿舍号" prop="dormNumber">
        <el-input
          v-model="queryParams.dormNumber"
          placeholder="请输入宿舍号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否住满" prop="isEmpty">
        <el-select
      v-model="queryParams.isEmpty"
      placeholder="请选择是否住满"
      clearable
      @keyup.enter.native="handleQuery"
    >
      <el-option label="宿舍未满" value="true" />
      <el-option label="宿舍已满" value="false" />
    </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="dormitoryList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="宿舍号" align="center" prop="dormNumber" />
      <el-table-column label="所属楼宇" align="center" prop="buildingName" />
      <el-table-column label="最大可住人数" align="center" prop="maxCapacity" />
      <el-table-column
        label="已住人数"
        align="center"
        prop="currentOccupancy"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- 添加或修改宿舍信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="宿舍号" prop="dormNumber" label-width="120px">
          <el-input v-model="form.dormNumber" placeholder="请输入宿舍号" />
        </el-form-item>
        <el-form-item label="所属楼栋" prop="buildingId" label-width="120px">
          <el-select
            v-model="form.buildingId"
            filterable
            placeholder="请选择所属楼栋"
          >
            <el-option
              v-for="item in buildingList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="最大可住人数"
          prop="maxCapacity"
          label-width="120px"
        >
          <el-input-number
            v-model="form.maxCapacity"
            :min="form.currentOccupancy != null ? form.currentOccupancy : 1"
            :max="10"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  listDormitory,
  getDormitory,
  delDormitory,
  addDormitory,
  updateDormitory,
} from "@/api/dorm";
import { loadAllParams } from "@/api/all";
import { listBuilding } from "@/api/building";
export default {
  name: "DormitoryView",
  data() {
    return {
      buildingList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 宿舍信息表格数据
      dormitoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        page: 1,
        pageSize: 10,
        dormNumber: null,
        buildingId: null,
        isEmpty: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        dormNumber: [
          { required: true, message: "宿舍号不能为空", trigger: "blur" },
        ],
        buildingId: [
          { required: true, message: "所属楼宇ID不能为空", trigger: "change" },
        ],
        maxCapacity: [
          { required: true, message: "最大可住人数不能为空", trigger: "blur" },
        ],
        currentOccupancy: [
          { required: true, message: "已住人数不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.loadAllBuilding();
  },
  methods: {
    // 重置表单验证状态
    resetFormValidation() {
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },
    /** 查询宿舍信息列表 */
    getList() {
      this.loading = true;
      listDormitory(this.queryParams).then((response) => {
        if(response.data.code === 200){
          this.dormitoryList = response.data.data.rows;
          this.total = response.data.data.total;
          this.loading = false;
        }else{
          this.$message({
                type: "warning",
                message: response.data.msg,
              });
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        dormNumber: null,
        buildingId: null,
        maxCapacity: null,
        currentOccupancy: null,
        createTime: null,
        updateTime: null,
        isEmpty: null,
      };
      this.resetFormValidation(); // 重置表单验证状态
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加宿舍信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getDormitory(id).then((response) => {
        if(response.data.code !== 200){
          this.$message({
                type: "warning",
                message: response.data.msg,
              });
          return;
        }
        this.form = response.data.data;
        this.open = true;
        this.title = "修改宿舍信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateDormitory(this.form).then((resp) => {
              if (resp.data.code !== 200) {
                this.$message({
                  message: resp.data.msg,
                  type: "warning",
                });
                this.open = false;
                this.getList();
                return;
              }
              this.$message({
                message: "修改成功",
                type: "success",
              });
              this.open = false;
              this.getList();
            });
          } else {
            addDormitory(this.form).then((response) => {
              if (response.data.code === 200) {
                this.$message({
                  message: "添加成功",
                  type: "success",
                });
                this.open = false;
                this.getList();
              }else{
                this.$message({
                  message: "response.data.msg",
                  type: "warning",
                });
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        '是否确认删除宿舍？',
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          delDormitory(ids).then((response) => {
            if (response.data.code === 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getList();
            }else{
              this.$message({
                type: "warning",
                message: response.data.msg,
              });
            }
          });

        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    /* 查询所有楼宇信息 */
    loadAllBuilding() {
      listBuilding(loadAllParams).then((response) => {
        this.buildingList = response.data.data.rows;
      });
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.page = val;
      this.getList();
    },
  },
};
</script>
